import React from 'react'
import { Token } from './config'

// 测试环境
const baseUrl = import.meta.env.VITE_BASEURL

async function request({ method = 'get', url, data, ...option }) {
  method = method.toUpperCase()

  const token = Token.get()

  // if (!token && !/^\/login/.test(location.pathname)) {
  //   location.href = '/login'
  //   return
  // }

  /** @type {RequestInit} */
  let optionObj = {
    method,
    headers: {
      Authorization: token,
      ...option.headers
    },
    ...option
  }

  if (method === 'GET' && data) {
    let paramsArray = []
    Object.keys(data).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(data[key])))
    if (url.search(/\?/) === -1) {
      typeof data === 'object' && (url += '?' + paramsArray.join('&'))
    } else {
      url += '&' + paramsArray.join('&')
    }
  }

  if (['PUT', 'POST'].includes(method) && data) {
    optionObj.body = JSON.stringify(data)
  }

  try {
    const response = await fetch(baseUrl + url, optionObj)

    const res = await response.json()

    const responseCode = Number(res.code)

    switch (responseCode) {
      case 200:
        // 将返回null统一转成undefined
        return Promise.resolve(res.data ?? undefined)
      case 40100:
        React.$message.error(res.msg)
        location.href = '/login'
        Token.remove()
      // eslint-disable-next-line no-fallthrough
      default:
        React.$message.destroy()

        if (res.msg) {
          React.$message.error(res.msg)
          return Promise.reject(res.msg)
        }
        break
    }
  } catch (error) {
    React.$message.error(error.toString())

    return Promise.reject(error)
  }
}

export default request
